package com.w3coffee.web.control;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;

import com.w3coffee.web.Branch;
import com.w3coffee.web.oauth.IOauthApi;
import com.w3coffee.web.oauth.OauthFactory;

public class OauthRequestController extends BaseController {
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	public ModelAndView handleRequest(HttpServletRequest req,
			HttpServletResponse resp) throws Exception {
		Map<String, Object> model = getDefaultModel(req);
		HttpSession session = req.getSession();
		CheckinToken token = (CheckinToken) session.getAttribute("TOKEN");
		if (token == null) {
			return adaptive(req, resp, "welcome", model);
		}

		String host = (String) req.getParameter("host");
		OauthFactory factory = (OauthFactory) getBean("oauthFactory");
		IOauthApi authApi = factory.getOAuth(host);
		if (authApi == null) {
			logger.error("Cannot found authenticator for host [" + host + "]");
			return adaptive(req, resp, "welcome", model);
		}
		
		double lng = token.getLongitude();
		double lat = token.getLatitude();
		double acy = token.getAccuracy();
		
		Branch branch = ContextServlet.getBranch(lng, lat, acy);
		if (branch == null) {
			return adaptive(req, resp, "toofar", getDefaultModel(req));
		} else {
			token.setBranch(branch);
		}

		String callbackUrl = getBaseUrl(req) + "/oacb.sf?host=" + host;
		authApi.oauthRequest(req, resp, callbackUrl);
		return null;
	}

}
